<template>
  <div class="map">
    <nav-bar></nav-bar>
    <van-search
      v-model="searchVal"
      placeholder="请输入搜索关键词"
      @change="getPosition"
    />
    <ul class="list">
      <li
        class="item"
        v-for="(item, index) in positionList"
        :key="index"
        @click="toHome(item)"
      >
        {{ item.title }}
      </li>
    </ul>
    <div id="allmap"></div>
  </div>
</template>
<script>
import NavBar from "@/components/common/nav-bar";
export default {
  data() {
    return {
      map: {},
      searchVal: "",
      positionList: [],
    };
  },
  methods: {
    baiduMapInit() {
      var map = new BMap.Map("allmap");
      var point = new BMap.Point(116.404, 39.915);
      map.centerAndZoom(point, 15);

      if (this.$store.state.home.lng !== 0) {
        map.clearOverlays();
        var new_point = new BMap.Point(
          this.$store.state.home.lng,
          this.$store.state.home.lat
        );
        map.panTo(new_point);
      } else {
        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(
          function (r) {
            if (this.getStatus() == BMAP_STATUS_SUCCESS) {
              var mk = new BMap.Marker(r.point);
              map.addOverlay(mk);
              map.panTo(r.point);
            } else {
              alert("failed" + this.getStatus());
            }
          },
          { enableHighAccuracy: true }
        );
      }

      this.map = map;
    },

    getPosition() {
      let _this = this;
      var map = this.map;
      _this.positionList = [];

      let options = {
        onSearchComplete: function (results) {
          // 判断状态是否正确
          if (local.getStatus() == BMAP_STATUS_SUCCESS) {
            for (var i = 0; i < results.getCurrentNumPois(); i++) {
              _this.positionList.push(results.Hr[i]);
            }
          }
        },
      };
      var local = new BMap.LocalSearch(map, options);
      local.search(_this.searchVal);
    },

    toHome(item) {
      this.$router.push("/home");
      console.log(item.point);
      this.$store.commit("home/getPosition", item);
    },
  },
  mounted() {
    this.baiduMapInit();
  },
  components: {
    "nav-bar": NavBar,
  },
};
</script>

<style lang="scss" scoped>
.map {
  position: relative;
  min-height: calc(100vh - 100px);
}
#allmap {
  width: 100%;
  height: 200px;
  overflow: hidden;
  margin: 0;
  font-family: "微软雅黑";
}
.list {
  width: 100%;
  height: 330px;
  .item {
    background: #fff;
    height: 10%;
    text-align: center;
    line-height: 30px;
    box-sizing: border-box;
    border-bottom: 1px solid rgb(236, 236, 236);
  }
}
</style>